/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farent.solutions.plugins.stripes.hyperstripes.core;

import com.farent.solutions.plugins.stripes.hyperstripes.spi.RenderKit;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;

/**
 * Responsible for creating ComponentModels for tagNames
 * found in the View Description Language
 * @author farouka
 */
public class ComponentTagModelFactory
{
    private static Map<Class, ComponentTypeStateHelper> stateHelperMap;
    
    static
    {
        ComponentAnnotationProcessor.getInstance().startUp();
        stateHelperMap = new HashMap<Class, ComponentTypeStateHelper>();
    }
    private ComponentTagModelFactory()
    {
    }

    public static Map<Class, ComponentTypeStateHelper> getStateHelperMap() {
        return stateHelperMap;
    }

    /**
     * creates a model for the provided tagName. Each Model is different
     *
     * Also sets the ComponentHelper to ensure getComponentHelper does not return null
     * @param tagName
     * @return
     */
    public ComponentModel getTagModelForTag( QName qName,
            StripesApplicationContext applicationContext )
    {
        String tagName = qName.getLocalPart();
        String namespace = qName.getNamespaceURI();
        RenderKit renderkit = applicationContext.getRenderKit( namespace );
        if( renderkit == null )
            renderkit = HyperStripesRenderKit.getInstance();
        ComponentModel model = renderkit.getTagModelForTag( tagName );
        if( model != null )
        {
            ComponentTypeStateHelper stateHelper =
                    findComponentTypeStateHelper(model.getClass(), tagName, applicationContext);
            model.setComponentTypeStateHelper(stateHelper);
        }
        return model;
    }

    public static ComponentTagModelFactory getInstance()
    {
        return ComponentTagModelFactoryHolder.INSTANCE;
    }

    public static ComponentTypeStateHelper findComponentTypeStateHelper(
            Class class1, String tagname,StripesApplicationContext applicationContext )
    {
        ComponentTypeStateHelper helper =
                (DefaultComponentTypeStateHelper) stateHelperMap.get(class1);
        if( helper == null )
        {
            ComponentTypeStateHelperFactory statesHelperFactory =
                    ComponentTypeStateHelperFactory.getInstance();
            helper = statesHelperFactory.getStatesHandlerForComponent(class1, applicationContext);
            helper.setName(tagname);
            stateHelperMap.put(class1, helper);
        }
        return helper;
    }

    private static class ComponentTagModelFactoryHolder
    {
        private static final ComponentTagModelFactory INSTANCE =
                new ComponentTagModelFactory();
    }
}
